/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Ucop/Net/TcpListener.h"
#include <cassert>


namespace Ucop {
namespace Net {

    TcpListener::TcpListener(struct event_base *_Base, Callback _Callback, void *_Userptr /* = NULL */)
        : _Mybase(_Base)
        , _Myaccepter(NULL)
        , _Mycallback(_Callback)
        , _Myuserptr(_Userptr)
    {

    }

    TcpListener::~TcpListener(void)
    {
        _Uninitialize();
    }

    void TcpListener::Close(void)
    {
        if (_Myaccepter) {
            evconnlistener_free(_Myaccepter);
            _Myaccepter = NULL;
        }
    }

    bool TcpListener::Enable(bool _Enable)
    {
        UCOP_ASSERT(_Myaccepter);
        if (_Enable) {
            return evconnlistener_enable(_Myaccepter) == 0;
        }
        return evconnlistener_disable(_Myaccepter) == 0;
    }


    void TcpListener::_Uninitialize(void)
    {
        if (_Myaccepter)
        {
            evconnlistener_free(_Myaccepter);
            _Myaccepter = NULL;
        }
    }

    void TcpListener::_AcceptCallback(struct evconnlistener *_Listener, evutil_socket_t _Sock, struct sockaddr *_Addr, int _Addrlen, void *_Userptr)
    {
        TcpListener *_TcpListener = static_cast<TcpListener*>(_Userptr);
        UCOP_ASSERT(_TcpListener && _TcpListener->_Mycallback);
        _TcpListener->_Mycallback(_Sock, _Addr, _Addrlen, _TcpListener->_Myuserptr);
    }

}}